package org.cos.generation.util.xml;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.cos.generation.epda.Method;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class SRMTReader {

	public static List<Method> read(InputStream inputStream) throws Exception {
		try {
			DocumentBuilderFactory  factory=DocumentBuilderFactory.newInstance();
			DocumentBuilder builder;

			builder = factory. newDocumentBuilder();
			
			Document  document = builder.parse(inputStream);
			
			Element root = document.getDocumentElement();
			NodeList classNodes = root.getElementsByTagName("class");
			int classNum = classNodes.getLength();
			
			List<Method> methodList = new LinkedList<Method>();
			
			for (int i = 0; i < classNum; i++) {
				Element classElement = (Element)classNodes.item(i);
				
				String qualifiedType = classElement.getAttribute("name");
				
				NodeList methodNodes = classElement.getChildNodes();
				int methodNum = methodNodes.getLength();
				
				for (int j = 0; j < methodNum; j++) {
					
					Node methodNode = methodNodes.item(j);
					
					if (methodNode.getNodeName().equals("method")) {
						Element methodElement = (Element)methodNode;
						
						String simpleName = methodElement.getAttribute("name");
						
						NodeList paraNodes = methodElement.getChildNodes();
						int paraNum = paraNodes.getLength();
						
						List<String> paraList = new ArrayList<String>(paraNum);

						for (int k = 0; k < paraNum; k++) {
							Node paraNode = paraNodes.item(k);
							if (paraNode.getNodeName().equals("parameter")) {
								Element paraElement = (Element)paraNode;
								paraList.add(paraElement.getAttribute("type"));
							}
						}
						
						methodList.add(new Method(qualifiedType, simpleName, paraList, false));
					}
				}
			}
			
			return methodList;
			
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
	
}
